package info.tsukaworld.actor.mob;

import info.tsukaworld.actor.AnimatedActor;
import info.tsukaworld.grid.*;
import info.tsukaworld.actor.mob.pathfinding.*;
import info.tsukaworld.actor.Player;
import java.util.List;
import java.util.ArrayList;

public class Mob extends AnimatedActor
{
    private boolean aggro;
    private int aggroRadius;
    
    public Mob()
    {
        super();
        aggro = false;
        aggroRadius = 5;
    }
    
    public void act()//what the mob does on a single 'tick' of the program
    {
        if( !isMoving() )
        {
            processAggro();
            if(aggro)
                followPath();
            else
            {
                idleMove();
            }
        }
        super.act();
    }

    public void idleMove()
    {
        if( ((int)(Math.random() * 200 )) == 1 )
        {
            int direction = (int)(Math.random() * 4);
            for(int i = 0; i < 4; i ++)
            {
                if(canMove(direction * 90))
                {
                    setDirection(direction * 90);
                    startMove();
                    break;
                }
                direction++;
                direction = 7 % direction;
            }
        }
    }
    
     public void toggleAggro()
    { aggro = !aggro; }

    public void setAggro(boolean ag)
    { aggro = ag; }

    public boolean getAggro()
    { return aggro; }

    public void processAggro()
    {
        Location current = getLocation();
        Location target = getTargetLocation();
        if( current != null && target != null && Math.abs(current.getRow() - target.getRow()) < aggroRadius && Math.abs(current.getCol() - target.getCol())  < aggroRadius)
            aggro = true;
        else
            aggro = false;
    }

    public void followPath()
    {
        Maze m = new ModifiableMaze(getGrid());
        int area = getGrid().getNumRows() * getGrid().getNumCols();
        AStar a = new AStar(new SimpleHeuristicCalculator(area)); 
        Path p = a.findPath(m, getLocation(), getTargetLocation());
        List<Tile> list = p.getTiles();
        if( list.size() < 3)
        {
            setDirection(getLocation().getDirectionToward(getTargetLocation()));
            //attack();
        }
        else
        {
            Location loc = list.get(1).getLocation();
            setDirection(getLocation().getDirectionToward(loc));
            if(canMove())//&& currentHp > 0)  
                startMove();
        }
    }
    
    public Location getTargetLocation()
    { return getPlayerLocation(); }
    
    public Location getPlayerLocation()
    {
        ArrayList<Location> locs = getGrid().getOccupiedLocations();
        for(int i = 0; i < locs.size(); i++)
        {
            if(getGrid().get(locs.get(i)) instanceof Player)
                return locs.get(i);
        }
        return getLocation();
    }
    
    
}